/**
 * 微信公众号授权
 */
import Api from "@/api/index.js";
import reportApi from '@/api/modules/report'
import askLeaveApi from '@/api/modules/askLeave'
import store from "@/store";
import {getQueryString, getQrCodeId,getQrType} from "@/utils/index.js";
import * as consts from "@/utils/constant.js";
import {TYPE_ASK_LEAVE, TYPE, TYPE_ADDITIONAL_MATERIAL, TYPE_RESIGN, TYPE_INSURE_CANCEL, TYPE_SEC_INTERVIEW, STAFF_TYPE, TYPE_TAX} from "@/constant/index.js";
import dept from "../api/modules/dept";
import {handleGoTo} from './askLeaveRouter.js'
import {getUrlParam} from "./index";

class AuthInfo {
    constructor() {
        //应用授权作用域，弹出授权页面
        this.redirect_url = encodeURIComponent(location.href);
        this.wx_code = getQueryString("code");
        this.numList = [];
        this.stepType = 0;
        this.downloadShow = '0';
        // 当前类型
        this.type = ''
        // 当前面向员工类型,默认为1-全职
        this.staffType = 1
        // 是否开启税务认证
        this.enableTax = false
    }

    toAuth() {
        console.log('toAuth')
        let deptId = getQueryString("deptId");
        this.type = getQrType()
        this.staffType = getQueryString(STAFF_TYPE)
        store.commit("UPDATE_QR_CODE_TYPE", this.type);
        store.commit("UPDATE_STAFF_TYPE", this.staffType)
        store.commit("UPDATE_QR_CODE_ID", getQrCodeId())
        let appId;
        Api.user
            .getAppId({
                deptId,
            })
            .then((res) => {
                store.commit("UPDATE_SHOWLOADING", false);
                if (res.code != 200) {
                    uni.showToast({
                        title: res.msg,
                        icon: "error",
                    });
                    return;
                }
                //成功
                appId = window.location.href.includes('/xsdcrm-wechat-ui/')?res.data.appId:'wxe0ee816af068f3a4';

                uni.setStorageSync("appId", appId);

                // const currentPageRoute = this.$route.path;
                // console.log('当前页面路由:', currentPageRoute);

                let loginToken = uni.getStorageSync("token");
                console.log('this.redirect_url===>>>',this.redirect_url)
                let get_code_url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${this.redirect_url}&response_type=code&scope=${consts.SCOPE}&state=STATE&connect_redirect=1&#wechat_redirect`; //微信网页授权获取code
                if (!this.wx_code) {
                  uni.setStorageSync("ressssssss2", 'get_code_url');
                    window.location.href = get_code_url;
                    return;
                } else {
                  console.log(uni.getStorageSync("token"),'loginToken && loginToken != ""',(loginToken && loginToken != ""),loginToken)
                    if (loginToken && loginToken != "") {
                        // 查询入职流程状态
                        this.checkUserStatus();
                    } else {
                        this.toLogin(this.wx_code, deptId);
                    }
                }
            })

    }

    toLogin(code, deptId) {
        console.log("type==>",getUrlParam("type"))
        console.log("type==>",getQueryString("type"))
       let inductionType = 1
       if (getUrlParam("type") || getQueryString("type")) {
         inductionType = getUrlParam("type") || getQueryString("type")
       }
      if (inductionType == 'operateRegister') {
        inductionType = 2
      }else{
        inductionType = 1
      }
      console.log(inductionType)
        //微信免登录
        Api.user
            .withoutLogin({
                code,
                deptId,
                inductionType
                // inductionType: inductionType
            })
            .then(async (res) => {
                let {data} = res;

                store.commit("UPDATE_SHOWLOADING", false);
                this.numList = res.data.numList;
                uni.setStorageSync("numList", this.numList);
                if (data.loginFlag == "1") {
                    //成功
                    uni.setStorageSync("token", data.token);
                    uni.setStorageSync("openId", data.openid);
                    uni.setStorageSync("openidaa", data.openid);
                    data.openid && store.commit("UPDATE_OPENID", data.openid);
                    this.checkUserStatus();
                } else if (data.loginFlag == "2") {
                    //失败
                    store.commit("UPDATE_OPENID", data.openid);
                    store.commit("UPDATE_ROUTEURL", "/pages/register/index");
                }
            })

    }

    async logger(code, deptId, body) {
        let text = "微信登录埋点 ";
        text += "Code: " + code + " \n ";
        text += "DeptId: " + deptId + " \n ";
        text += 'Url: ' + window.location.href + ' \n ';
        text += "Error: " + body + " \n ";
        try {
            await reportApi.errorReport({error: text, appId: '', openId: '', deptId});
        } catch (e) {

        } finally {

        }
    }

    /** 查询入职流程状态 */
    async checkUserStatus() {
        // 判断是否为入职二维码
        const urlObject = new URL(window.location.href);
        const params = new URLSearchParams(urlObject.search);
        const paramsObject = {};
        params.forEach((value, key) => {
          paramsObject[key] = value;
        });
        if (paramsObject.invitationId && paramsObject.resumeId && paramsObject.isHomePage != 1) {
          uni.setStorageSync('onboarding',JSON.stringify(window.location.href))
          uni.reLaunch({
            url: `/pages/HomePage/webIndex?onboarding=1`
          })
          return
        }
        console.log('查询入职流程步骤')
        // 如果当前类型为请假,跳转到请假页面
        if (this.type === TYPE_ASK_LEAVE) {
            await handleGoTo()
            return
        }
        // 如果当前类型为补充资料,跳转到补充资料页面
        if (this.type === TYPE_ADDITIONAL_MATERIAL) {
            store.commit("UPDATE_ROUTEURL", "/pages/additional_material/index");
            return
        }
        // 如果当前类型为辞职,跳转到辞职页面
        if (this.type === TYPE_RESIGN) {
            store.commit("UPDATE_ROUTEURL", "/pages/resign/index");
            return
        }
        // 如果当前类型为弃保,跳转到弃保页面
        if (this.type === TYPE_INSURE_CANCEL) {
            store.commit("UPDATE_ROUTEURL", "/pages/insure_cancel/index");
            return
        }
        // 如果当前类型为复试申请,跳转到复试页面
        if (this.type === TYPE_SEC_INTERVIEW) {
            store.commit("UPDATE_ROUTEURL", "/pages/sec_interview/index");
            return
        }
        // 如果当前类型为税务认证,跳转到税务认证页面
        if (this.type === TYPE_TAX) {
          store.commit("UPDATE_ROUTEURL", "/pages/tax_verify/index");
          return
        }
        let inductionType = getUrlParam("type")?(getUrlParam("type") == 'operateRegister'?2:1): 1
        Api.riders.queryInductionFlowStatus({inductionType:inductionType}).then(async (res) => {
            let {situation} = res.data;
            this.stepType = res.data.stepType;
            store.commit("UPDATE_STEPTYPE", res.data.stepType);
            this.downloadShow = res.data.downloadShow;
            this.haveActivity = res.data.haveActivity;
            this.enableTax = res.data.enableTax;
            switch (situation) {
                case "01":
                    //无数据，跳注册页
                    store.commit("UPDATE_ROUTEURL", "/pages/verify/index");
                    break;
                case "02":
                    store.commit("UPDATE_ROUTEURL", "/pages/register/index");
                    break;
                case "03":
                    //跳注册页
                    store.commit("UPDATE_ROUTEURL", "/pages/register/index");
                    break;
                case "04":
                    await this.toPathByStatus(res.data);
                    break;
                default:
                    await this.logger('', res.data.deptId, '匹配入职流程状态失败' + JSON.stringify(res.data))
                    break;
            }
        })
            .catch(async (e) => {
                await this.logger('', deptId, '查询入职流程状态错误 ' + e)
            });
    }

    async toPathByStatus(data) {
        let {status, flag, deptId} = data;
        store.commit("UPDATE_DEPTID", deptId);
        let matchStatus = true
        let matchFlag = true
        switch (status) {
            case "10":
                //无数据，跳转到注册页
                store.commit("UPDATE_ROUTEURL", "/pages/register/index");
                break;
            case "20":
                //预审登记页
                store.commit("UPDATE_ROUTEURL", "/pages/yushen/index");
                // store.commit("UPDATE_ROUTEURL", "/pages/pdf/index");
                break;
            case "30":
                //待入职,
                this.checkInfoToStep();
                break;
            case "95":
                // 入职未成功
                store.commit("UPDATE_ROUTEURL", "/pages/induction_fail/index");
                break;
            case "99":
                //跳转注册页
                store.commit("UPDATE_ROUTEURL", "/pages/register/index");
                break;
            default:
                matchStatus = false
                break;
        }
        switch (flag) {
            case "A":
                //承揽协议页面
                store.commit("UPDATE_ROUTEURL", "/pages/pdf/index");
                break;
            case "B":
                //待发信平台注册页面
                store.commit("UPDATE_ROUTEURL", "/pages/faxin/index");
                break;
            case "C":
                //美团下载页
                store.commit("UPDATE_ROUTEURL", "/pages/download/index");
                break;
            case "E":
                //背景审核登记
                store.commit("UPDATE_ROUTEURL", "/pages/bg_check/index");
                break;
            case "D":
                //完成
                store.commit("UPDATE_ROUTEURL", "/pages/finish/index");
                break;
            default:
                matchFlag = false
                break;
        }
        if (matchStatus === false && matchFlag === false) {
            await this.logger('', deptId, '匹配入职流程Status失败' + JSON.stringify(data))
        }
    }

    checkInfoToStep() {
        Api.riders.inductionInfo().then((res) => {
            let {data} = res;
            this.updateInfoStatus(data);
        });
    }

    updateInfoStatus(data) {

        let {
            nations,
            sexs,
            highestEducations,
            emergencyContacts,
            inductionChannels,
            step,
            idCardNo,
            phonenumber,
            recommendChannel,
            recommendThirtyChannel
        } = data;
        store.commit("UPDATE_NATIONS", nations);
        store.commit("UPDATE_SEXS", sexs);
        store.commit("UPDATE_HIGHTEDU", highestEducations);
        store.commit("UPDATE_CONTACTS", emergencyContacts);
        store.commit("UPDATE_IDCARDNO", idCardNo);
        store.commit("UPDATE_RECOMMEND_CHANNEL", recommendChannel);
        store.commit("UPDATE_RECOMMEND_THIRTY_COMPANY_CHANNEL", recommendThirtyChannel);
        store.commit("UPDATE_USERINFO", data);
        this.toStep(step);
    }

    toStep(step) {
        switch (step) {
            case "1":
                // store.commit("UPDATE_ROUTEURL", "/pages/step_two/index");
                store.commit("UPDATE_ROUTEURL", "/pages/step_four/index");
                break;
            // case "2":
            //   store.commit("UPDATE_ROUTEURL", "/pages/step_three/index");
            //   break;
            // case "3":
            //   store.commit("UPDATE_ROUTEURL", "/pages/step_four/index");
            //   break;
            default:
                store.commit("UPDATE_ROUTEURL", "/pages/step_one/index");
                break;
        }
    }

    getNumList() {
        this.numList = uni.getStorageSync("numList");
        return this.numList;
    }

    getStepType() {
        return this.stepType;
    }

    getDownloadShow() {
        return this.downloadShow;
    }

    getActivity() {
        return this.haveActivity;
    }

    getEnableTax() {
      // 判断是否在微信小程序中打开
      if (window.__wxjs_environment === 'miniprogram') {
        return false
      }
      return this.enableTax
    }

}

export default new AuthInfo();
